
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>3. Kaleidoscope: Code generation to LLVM IR &#8212; LLVM 5 documentation</title>
    
    <link rel="stylesheet" href="../_static/llvm-theme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '5',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true,
        SOURCELINK_SUFFIX: '.txt'
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="4. Kaleidoscope: Adding JIT and Optimizer Support" href="LangImpl04.html" />
    <link rel="prev" title="2. Kaleidoscope: Implementing a Parser and AST" href="LangImpl02.html" />
<style type="text/css">
  table.right { float: right; margin-left: 20px; }
  table.right td { border: 1px solid #ccc; }
</style>

  </head>
  <body role="document">
<div class="logo">
  <a href="../index.html">
    <img src="../_static/logo.png"
         alt="LLVM Logo" width="250" height="88"/></a>
</div>

    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="LangImpl04.html" title="4. Kaleidoscope: Adding JIT and Optimizer Support"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="LangImpl02.html" title="2. Kaleidoscope: Implementing a Parser and AST"
             accesskey="P">previous</a> |</li>
  <li><a href="http://llvm.org/">LLVM Home</a>&nbsp;|&nbsp;</li>
  <li><a href="../index.html">Documentation</a>&raquo;</li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">LLVM Tutorial: Table of Contents</a> &#187;</li> 
      </ul>
    </div>


    <div class="document">
      <div class="documentwrapper">
          <div class="body" role="main">
            
  <div class="section" id="kaleidoscope-code-generation-to-llvm-ir">
<h1>3. Kaleidoscope: Code generation to LLVM IR<a class="headerlink" href="#kaleidoscope-code-generation-to-llvm-ir" title="Permalink to this headline">¶</a></h1>
<div class="contents local topic" id="contents">
<ul class="simple">
<li><a class="reference internal" href="#chapter-3-introduction" id="id1">Chapter 3 Introduction</a></li>
<li><a class="reference internal" href="#code-generation-setup" id="id2">Code Generation Setup</a></li>
<li><a class="reference internal" href="#expression-code-generation" id="id3">Expression Code Generation</a></li>
<li><a class="reference internal" href="#function-code-generation" id="id4">Function Code Generation</a></li>
<li><a class="reference internal" href="#driver-changes-and-closing-thoughts" id="id5">Driver Changes and Closing Thoughts</a></li>
<li><a class="reference internal" href="#full-code-listing" id="id6">Full Code Listing</a></li>
</ul>
</div>
<div class="section" id="chapter-3-introduction">
<h2><a class="toc-backref" href="#id1">3.1. Chapter 3 Introduction</a><a class="headerlink" href="#chapter-3-introduction" title="Permalink to this headline">¶</a></h2>
<p>Welcome to Chapter 3 of the &#8220;<a class="reference external" href="index.html">Implementing a language with
LLVM</a>&#8221; tutorial. This chapter shows you how to transform
the <a class="reference external" href="LangImpl2.html">Abstract Syntax Tree</a>, built in Chapter 2, into
LLVM IR. This will teach you a little bit about how LLVM does things, as
well as demonstrate how easy it is to use. It&#8217;s much more work to build
a lexer and parser than it is to generate LLVM IR code. :)</p>
<p><strong>Please note</strong>: the code in this chapter and later require LLVM 3.7 or
later. LLVM 3.6 and before will not work with it. Also note that you
need to use a version of this tutorial that matches your LLVM release:
If you are using an official LLVM release, use the version of the
documentation included with your release or on the <a class="reference external" href="http://llvm.org/releases/">llvm.org releases
page</a>.</p>
</div>
<div class="section" id="code-generation-setup">
<h2><a class="toc-backref" href="#id2">3.2. Code Generation Setup</a><a class="headerlink" href="#code-generation-setup" title="Permalink to this headline">¶</a></h2>
<p>In order to generate LLVM IR, we want some simple setup to get started.
First we define virtual code generation (codegen) methods in each AST
class:</p>
<div class="highlight-c++"><div class="highlight"><pre><span></span><span class="c1">/// ExprAST - Base class for all expression nodes.</span>
<span class="k">class</span> <span class="nc">ExprAST</span> <span class="p">{</span>
<span class="k">public</span><span class="o">:</span>
  <span class="k">virtual</span> <span class="o">~</span><span class="n">ExprAST</span><span class="p">()</span> <span class="p">{}</span>
  <span class="k">virtual</span> <span class="n">Value</span> <span class="o">*</span><span class="n">codegen</span><span class="p">()</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">};</span>

<span class="c1">/// NumberExprAST - Expression class for numeric literals like &quot;1.0&quot;.</span>
<span class="k">class</span> <span class="nc">NumberExprAST</span> <span class="o">:</span> <span class="k">public</span> <span class="n">ExprAST</span> <span class="p">{</span>
  <span class="kt">double</span> <span class="n">Val</span><span class="p">;</span>

<span class="k">public</span><span class="o">:</span>
  <span class="n">NumberExprAST</span><span class="p">(</span><span class="kt">double</span> <span class="n">Val</span><span class="p">)</span> <span class="o">:</span> <span class="n">Val</span><span class="p">(</span><span class="n">Val</span><span class="p">)</span> <span class="p">{}</span>
  <span class="k">virtual</span> <span class="n">Value</span> <span class="o">*</span><span class="n">codegen</span><span class="p">();</span>
<span class="p">};</span>
<span class="p">...</span>
</pre></div>
</div>
<p>The codegen() method says to emit IR for that AST node along with all
the things it depends on, and they all return an LLVM Value object.
&#8220;Value&#8221; is the class used to represent a &#8220;<a class="reference external" href="http://en.wikipedia.org/wiki/Static_single_assignment_form">Static Single Assignment
(SSA)</a>
register&#8221; or &#8220;SSA value&#8221; in LLVM. The most distinct aspect of SSA values
is that their value is computed as the related instruction executes, and
it does not get a new value until (and if) the instruction re-executes.
In other words, there is no way to &#8220;change&#8221; an SSA value. For more
information, please read up on <a class="reference external" href="http://en.wikipedia.org/wiki/Static_single_assignment_form">Static Single
Assignment</a>
- the concepts are really quite natural once you grok them.</p>
<p>Note that instead of adding virtual methods to the ExprAST class
hierarchy, it could also make sense to use a <a class="reference external" href="http://en.wikipedia.org/wiki/Visitor_pattern">visitor
pattern</a> or some other
way to model this. Again, this tutorial won&#8217;t dwell on good software
engineering practices: for our purposes, adding a virtual method is
simplest.</p>
<p>The second thing we want is an &#8220;LogError&#8221; method like we used for the
parser, which will be used to report errors found during code generation
(for example, use of an undeclared parameter):</p>
<div class="highlight-c++"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">LLVMContext</span> <span class="n">TheContext</span><span class="p">;</span>
<span class="k">static</span> <span class="n">IRBuilder</span><span class="o">&lt;&gt;</span> <span class="n">Builder</span><span class="p">(</span><span class="n">TheContext</span><span class="p">);</span>
<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">Module</span><span class="o">&gt;</span> <span class="n">TheModule</span><span class="p">;</span>
<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">map</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="p">,</span> <span class="n">Value</span> <span class="o">*&gt;</span> <span class="n">NamedValues</span><span class="p">;</span>

<span class="n">Value</span> <span class="o">*</span><span class="nf">LogErrorV</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">Str</span><span class="p">)</span> <span class="p">{</span>
  <span class="n">LogError</span><span class="p">(</span><span class="n">Str</span><span class="p">);</span>
  <span class="k">return</span> <span class="k">nullptr</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The static variables will be used during code generation. <code class="docutils literal"><span class="pre">TheContext</span></code>
is an opaque object that owns a lot of core LLVM data structures, such as
the type and constant value tables. We don&#8217;t need to understand it in
detail, we just need a single instance to pass into APIs that require it.</p>
<p>The <code class="docutils literal"><span class="pre">Builder</span></code> object is a helper object that makes it easy to generate
LLVM instructions. Instances of the
<a class="reference external" href="http://llvm.org/doxygen/IRBuilder_8h-source.html">IRBuilder</a>
class template keep track of the current place to insert instructions
and has methods to create new instructions.</p>
<p><code class="docutils literal"><span class="pre">TheModule</span></code> is an LLVM construct that contains functions and global
variables. In many ways, it is the top-level structure that the LLVM IR
uses to contain code. It will own the memory for all of the IR that we
generate, which is why the codegen() method returns a raw Value*,
rather than a unique_ptr&lt;Value&gt;.</p>
<p>The <code class="docutils literal"><span class="pre">NamedValues</span></code> map keeps track of which values are defined in the
current scope and what their LLVM representation is. (In other words, it
is a symbol table for the code). In this form of Kaleidoscope, the only
things that can be referenced are function parameters. As such, function
parameters will be in this map when generating code for their function
body.</p>
<p>With these basics in place, we can start talking about how to generate
code for each expression. Note that this assumes that the <code class="docutils literal"><span class="pre">Builder</span></code>
has been set up to generate code <em>into</em> something. For now, we&#8217;ll assume
that this has already been done, and we&#8217;ll just use it to emit code.</p>
</div>
<div class="section" id="expression-code-generation">
<h2><a class="toc-backref" href="#id3">3.3. Expression Code Generation</a><a class="headerlink" href="#expression-code-generation" title="Permalink to this headline">¶</a></h2>
<p>Generating LLVM code for expression nodes is very straightforward: less
than 45 lines of commented code for all four of our expression nodes.
First we&#8217;ll do numeric literals:</p>
<div class="highlight-c++"><div class="highlight"><pre><span></span><span class="n">Value</span> <span class="o">*</span><span class="n">NumberExprAST</span><span class="o">::</span><span class="n">codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">return</span> <span class="n">ConstantFP</span><span class="o">::</span><span class="n">get</span><span class="p">(</span><span class="n">TheContext</span><span class="p">,</span> <span class="n">APFloat</span><span class="p">(</span><span class="n">Val</span><span class="p">));</span>
<span class="p">}</span>
</pre></div>
</div>
<p>In the LLVM IR, numeric constants are represented with the
<code class="docutils literal"><span class="pre">ConstantFP</span></code> class, which holds the numeric value in an <code class="docutils literal"><span class="pre">APFloat</span></code>
internally (<code class="docutils literal"><span class="pre">APFloat</span></code> has the capability of holding floating point
constants of Arbitrary Precision). This code basically just creates
and returns a <code class="docutils literal"><span class="pre">ConstantFP</span></code>. Note that in the LLVM IR that constants
are all uniqued together and shared. For this reason, the API uses the
&#8220;foo::get(...)&#8221; idiom instead of &#8220;new foo(..)&#8221; or &#8220;foo::Create(..)&#8221;.</p>
<div class="highlight-c++"><div class="highlight"><pre><span></span><span class="n">Value</span> <span class="o">*</span><span class="n">VariableExprAST</span><span class="o">::</span><span class="n">codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="c1">// Look this variable up in the function.</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">V</span> <span class="o">=</span> <span class="n">NamedValues</span><span class="p">[</span><span class="n">Name</span><span class="p">];</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">V</span><span class="p">)</span>
    <span class="n">LogErrorV</span><span class="p">(</span><span class="s">&quot;Unknown variable name&quot;</span><span class="p">);</span>
  <span class="k">return</span> <span class="n">V</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>References to variables are also quite simple using LLVM. In the simple
version of Kaleidoscope, we assume that the variable has already been
emitted somewhere and its value is available. In practice, the only
values that can be in the <code class="docutils literal"><span class="pre">NamedValues</span></code> map are function arguments.
This code simply checks to see that the specified name is in the map (if
not, an unknown variable is being referenced) and returns the value for
it. In future chapters, we&#8217;ll add support for <a class="reference external" href="LangImpl5.html#for-loop-expression">loop induction
variables</a> in the symbol table, and for <a class="reference external" href="LangImpl7.html#user-defined-local-variables">local
variables</a>.</p>
<div class="highlight-c++"><div class="highlight"><pre><span></span><span class="n">Value</span> <span class="o">*</span><span class="n">BinaryExprAST</span><span class="o">::</span><span class="n">codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">L</span> <span class="o">=</span> <span class="n">LHS</span><span class="o">-&gt;</span><span class="n">codegen</span><span class="p">();</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">R</span> <span class="o">=</span> <span class="n">RHS</span><span class="o">-&gt;</span><span class="n">codegen</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">L</span> <span class="o">||</span> <span class="o">!</span><span class="n">R</span><span class="p">)</span>
    <span class="k">return</span> <span class="k">nullptr</span><span class="p">;</span>

  <span class="k">switch</span> <span class="p">(</span><span class="n">Op</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">case</span> <span class="sc">&#39;+&#39;</span><span class="o">:</span>
    <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFAdd</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">R</span><span class="p">,</span> <span class="s">&quot;addtmp&quot;</span><span class="p">);</span>
  <span class="k">case</span> <span class="sc">&#39;-&#39;</span><span class="o">:</span>
    <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFSub</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">R</span><span class="p">,</span> <span class="s">&quot;subtmp&quot;</span><span class="p">);</span>
  <span class="k">case</span> <span class="sc">&#39;*&#39;</span><span class="o">:</span>
    <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFMul</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">R</span><span class="p">,</span> <span class="s">&quot;multmp&quot;</span><span class="p">);</span>
  <span class="k">case</span> <span class="sc">&#39;&lt;&#39;</span><span class="o">:</span>
    <span class="n">L</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFCmpULT</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">R</span><span class="p">,</span> <span class="s">&quot;cmptmp&quot;</span><span class="p">);</span>
    <span class="c1">// Convert bool 0/1 to double 0.0 or 1.0</span>
    <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateUIToFP</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">Type</span><span class="o">::</span><span class="n">getDoubleTy</span><span class="p">(</span><span class="n">TheContext</span><span class="p">),</span>
                                <span class="s">&quot;booltmp&quot;</span><span class="p">);</span>
  <span class="k">default</span><span class="o">:</span>
    <span class="k">return</span> <span class="n">LogErrorV</span><span class="p">(</span><span class="s">&quot;invalid binary operator&quot;</span><span class="p">);</span>
  <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Binary operators start to get more interesting. The basic idea here is
that we recursively emit code for the left-hand side of the expression,
then the right-hand side, then we compute the result of the binary
expression. In this code, we do a simple switch on the opcode to create
the right LLVM instruction.</p>
<p>In the example above, the LLVM builder class is starting to show its
value. IRBuilder knows where to insert the newly created instruction,
all you have to do is specify what instruction to create (e.g. with
<code class="docutils literal"><span class="pre">CreateFAdd</span></code>), which operands to use (<code class="docutils literal"><span class="pre">L</span></code> and <code class="docutils literal"><span class="pre">R</span></code> here) and
optionally provide a name for the generated instruction.</p>
<p>One nice thing about LLVM is that the name is just a hint. For instance,
if the code above emits multiple &#8220;addtmp&#8221; variables, LLVM will
automatically provide each one with an increasing, unique numeric
suffix. Local value names for instructions are purely optional, but it
makes it much easier to read the IR dumps.</p>
<p><a class="reference external" href="../LangRef.html#instruction-reference">LLVM instructions</a> are constrained by strict
rules: for example, the Left and Right operators of an <a class="reference external" href="../LangRef.html#add-instruction">add
instruction</a> must have the same type, and the
result type of the add must match the operand types. Because all values
in Kaleidoscope are doubles, this makes for very simple code for add,
sub and mul.</p>
<p>On the other hand, LLVM specifies that the <a class="reference external" href="../LangRef.html#fcmp-instruction">fcmp
instruction</a> always returns an &#8216;i1&#8217; value (a
one bit integer). The problem with this is that Kaleidoscope wants the
value to be a 0.0 or 1.0 value. In order to get these semantics, we
combine the fcmp instruction with a <a class="reference external" href="../LangRef.html#uitofp-to-instruction">uitofp
instruction</a>. This instruction converts its
input integer into a floating point value by treating the input as an
unsigned value. In contrast, if we used the <a class="reference external" href="../LangRef.html#sitofp-to-instruction">sitofp
instruction</a>, the Kaleidoscope &#8216;&lt;&#8217; operator
would return 0.0 and -1.0, depending on the input value.</p>
<div class="highlight-c++"><div class="highlight"><pre><span></span><span class="n">Value</span> <span class="o">*</span><span class="n">CallExprAST</span><span class="o">::</span><span class="n">codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="c1">// Look up the name in the global module table.</span>
  <span class="n">Function</span> <span class="o">*</span><span class="n">CalleeF</span> <span class="o">=</span> <span class="n">TheModule</span><span class="o">-&gt;</span><span class="n">getFunction</span><span class="p">(</span><span class="n">Callee</span><span class="p">);</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">CalleeF</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">LogErrorV</span><span class="p">(</span><span class="s">&quot;Unknown function referenced&quot;</span><span class="p">);</span>

  <span class="c1">// If argument mismatch error.</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">CalleeF</span><span class="o">-&gt;</span><span class="n">arg_size</span><span class="p">()</span> <span class="o">!=</span> <span class="n">Args</span><span class="p">.</span><span class="n">size</span><span class="p">())</span>
    <span class="k">return</span> <span class="n">LogErrorV</span><span class="p">(</span><span class="s">&quot;Incorrect # arguments passed&quot;</span><span class="p">);</span>

  <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">Value</span> <span class="o">*&gt;</span> <span class="n">ArgsV</span><span class="p">;</span>
  <span class="k">for</span> <span class="p">(</span><span class="kt">unsigned</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="n">e</span> <span class="o">=</span> <span class="n">Args</span><span class="p">.</span><span class="n">size</span><span class="p">();</span> <span class="n">i</span> <span class="o">!=</span> <span class="n">e</span><span class="p">;</span> <span class="o">++</span><span class="n">i</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">ArgsV</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="n">Args</span><span class="p">[</span><span class="n">i</span><span class="p">]</span><span class="o">-&gt;</span><span class="n">codegen</span><span class="p">());</span>
    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">ArgsV</span><span class="p">.</span><span class="n">back</span><span class="p">())</span>
      <span class="k">return</span> <span class="k">nullptr</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateCall</span><span class="p">(</span><span class="n">CalleeF</span><span class="p">,</span> <span class="n">ArgsV</span><span class="p">,</span> <span class="s">&quot;calltmp&quot;</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Code generation for function calls is quite straightforward with LLVM. The code
above initially does a function name lookup in the LLVM Module&#8217;s symbol table.
Recall that the LLVM Module is the container that holds the functions we are
JIT&#8217;ing. By giving each function the same name as what the user specifies, we
can use the LLVM symbol table to resolve function names for us.</p>
<p>Once we have the function to call, we recursively codegen each argument
that is to be passed in, and create an LLVM <a class="reference external" href="../LangRef.html#call-instruction">call
instruction</a>. Note that LLVM uses the native C
calling conventions by default, allowing these calls to also call into
standard library functions like &#8220;sin&#8221; and &#8220;cos&#8221;, with no additional
effort.</p>
<p>This wraps up our handling of the four basic expressions that we have so
far in Kaleidoscope. Feel free to go in and add some more. For example,
by browsing the <a class="reference external" href="../LangRef.html">LLVM language reference</a> you&#8217;ll find
several other interesting instructions that are really easy to plug into
our basic framework.</p>
</div>
<div class="section" id="function-code-generation">
<h2><a class="toc-backref" href="#id4">3.4. Function Code Generation</a><a class="headerlink" href="#function-code-generation" title="Permalink to this headline">¶</a></h2>
<p>Code generation for prototypes and functions must handle a number of
details, which make their code less beautiful than expression code
generation, but allows us to illustrate some important points. First,
lets talk about code generation for prototypes: they are used both for
function bodies and external function declarations. The code starts
with:</p>
<div class="highlight-c++"><div class="highlight"><pre><span></span><span class="n">Function</span> <span class="o">*</span><span class="n">PrototypeAST</span><span class="o">::</span><span class="n">codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="c1">// Make the function type:  double(double,double) etc.</span>
  <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">Type</span><span class="o">*&gt;</span> <span class="n">Doubles</span><span class="p">(</span><span class="n">Args</span><span class="p">.</span><span class="n">size</span><span class="p">(),</span>
                             <span class="n">Type</span><span class="o">::</span><span class="n">getDoubleTy</span><span class="p">(</span><span class="n">TheContext</span><span class="p">));</span>
  <span class="n">FunctionType</span> <span class="o">*</span><span class="n">FT</span> <span class="o">=</span>
    <span class="n">FunctionType</span><span class="o">::</span><span class="n">get</span><span class="p">(</span><span class="n">Type</span><span class="o">::</span><span class="n">getDoubleTy</span><span class="p">(</span><span class="n">TheContext</span><span class="p">),</span> <span class="n">Doubles</span><span class="p">,</span> <span class="nb">false</span><span class="p">);</span>

  <span class="n">Function</span> <span class="o">*</span><span class="n">F</span> <span class="o">=</span>
    <span class="n">Function</span><span class="o">::</span><span class="n">Create</span><span class="p">(</span><span class="n">FT</span><span class="p">,</span> <span class="n">Function</span><span class="o">::</span><span class="n">ExternalLinkage</span><span class="p">,</span> <span class="n">Name</span><span class="p">,</span> <span class="n">TheModule</span><span class="p">);</span>
</pre></div>
</div>
<p>This code packs a lot of power into a few lines. Note first that this
function returns a &#8220;Function*&#8221; instead of a &#8220;Value*&#8221;. Because a
&#8220;prototype&#8221; really talks about the external interface for a function
(not the value computed by an expression), it makes sense for it to
return the LLVM Function it corresponds to when codegen&#8217;d.</p>
<p>The call to <code class="docutils literal"><span class="pre">FunctionType::get</span></code> creates the <code class="docutils literal"><span class="pre">FunctionType</span></code> that
should be used for a given Prototype. Since all function arguments in
Kaleidoscope are of type double, the first line creates a vector of &#8220;N&#8221;
LLVM double types. It then uses the <code class="docutils literal"><span class="pre">Functiontype::get</span></code> method to
create a function type that takes &#8220;N&#8221; doubles as arguments, returns one
double as a result, and that is not vararg (the false parameter
indicates this). Note that Types in LLVM are uniqued just like Constants
are, so you don&#8217;t &#8220;new&#8221; a type, you &#8220;get&#8221; it.</p>
<p>The final line above actually creates the IR Function corresponding to
the Prototype. This indicates the type, linkage and name to use, as
well as which module to insert into. &#8220;<a class="reference external" href="../LangRef.html#linkage">external
linkage</a>&#8221; means that the function may be
defined outside the current module and/or that it is callable by
functions outside the module. The Name passed in is the name the user
specified: since &#8220;<code class="docutils literal"><span class="pre">TheModule</span></code>&#8221; is specified, this name is registered
in &#8220;<code class="docutils literal"><span class="pre">TheModule</span></code>&#8220;s symbol table.</p>
<div class="highlight-c++"><div class="highlight"><pre><span></span><span class="c1">// Set names for all arguments.</span>
<span class="kt">unsigned</span> <span class="n">Idx</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="k">for</span> <span class="p">(</span><span class="k">auto</span> <span class="o">&amp;</span><span class="nl">Arg</span> <span class="p">:</span> <span class="n">F</span><span class="o">-&gt;</span><span class="n">args</span><span class="p">())</span>
  <span class="n">Arg</span><span class="p">.</span><span class="n">setName</span><span class="p">(</span><span class="n">Args</span><span class="p">[</span><span class="n">Idx</span><span class="o">++</span><span class="p">]);</span>

<span class="k">return</span> <span class="n">F</span><span class="p">;</span>
</pre></div>
</div>
<p>Finally, we set the name of each of the function&#8217;s arguments according to the
names given in the Prototype. This step isn&#8217;t strictly necessary, but keeping
the names consistent makes the IR more readable, and allows subsequent code to
refer directly to the arguments for their names, rather than having to look up
them up in the Prototype AST.</p>
<p>At this point we have a function prototype with no body. This is how LLVM IR
represents function declarations. For extern statements in Kaleidoscope, this
is as far as we need to go. For function definitions however, we need to
codegen and attach a function body.</p>
<div class="highlight-c++"><div class="highlight"><pre><span></span><span class="n">Function</span> <span class="o">*</span><span class="n">FunctionAST</span><span class="o">::</span><span class="n">codegen</span><span class="p">()</span> <span class="p">{</span>
    <span class="c1">// First, check for an existing function from a previous &#39;extern&#39; declaration.</span>
  <span class="n">Function</span> <span class="o">*</span><span class="n">TheFunction</span> <span class="o">=</span> <span class="n">TheModule</span><span class="o">-&gt;</span><span class="n">getFunction</span><span class="p">(</span><span class="n">Proto</span><span class="o">-&gt;</span><span class="n">getName</span><span class="p">());</span>

  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">TheFunction</span><span class="p">)</span>
    <span class="n">TheFunction</span> <span class="o">=</span> <span class="n">Proto</span><span class="o">-&gt;</span><span class="n">codegen</span><span class="p">();</span>

  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">TheFunction</span><span class="p">)</span>
    <span class="k">return</span> <span class="k">nullptr</span><span class="p">;</span>

  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">TheFunction</span><span class="o">-&gt;</span><span class="n">empty</span><span class="p">())</span>
    <span class="k">return</span> <span class="p">(</span><span class="n">Function</span><span class="o">*</span><span class="p">)</span><span class="n">LogErrorV</span><span class="p">(</span><span class="s">&quot;Function cannot be redefined.&quot;</span><span class="p">);</span>
</pre></div>
</div>
<p>For function definitions, we start by searching TheModule&#8217;s symbol table for an
existing version of this function, in case one has already been created using an
&#8216;extern&#8217; statement. If Module::getFunction returns null then no previous version
exists, so we&#8217;ll codegen one from the Prototype. In either case, we want to
assert that the function is empty (i.e. has no body yet) before we start.</p>
<div class="highlight-c++"><div class="highlight"><pre><span></span><span class="c1">// Create a new basic block to start insertion into.</span>
<span class="n">BasicBlock</span> <span class="o">*</span><span class="n">BB</span> <span class="o">=</span> <span class="n">BasicBlock</span><span class="o">::</span><span class="n">Create</span><span class="p">(</span><span class="n">TheContext</span><span class="p">,</span> <span class="s">&quot;entry&quot;</span><span class="p">,</span> <span class="n">TheFunction</span><span class="p">);</span>
<span class="n">Builder</span><span class="p">.</span><span class="n">SetInsertPoint</span><span class="p">(</span><span class="n">BB</span><span class="p">);</span>

<span class="c1">// Record the function arguments in the NamedValues map.</span>
<span class="n">NamedValues</span><span class="p">.</span><span class="n">clear</span><span class="p">();</span>
<span class="k">for</span> <span class="p">(</span><span class="k">auto</span> <span class="o">&amp;</span><span class="nl">Arg</span> <span class="p">:</span> <span class="n">TheFunction</span><span class="o">-&gt;</span><span class="n">args</span><span class="p">())</span>
  <span class="n">NamedValues</span><span class="p">[</span><span class="n">Arg</span><span class="p">.</span><span class="n">getName</span><span class="p">()]</span> <span class="o">=</span> <span class="o">&amp;</span><span class="n">Arg</span><span class="p">;</span>
</pre></div>
</div>
<p>Now we get to the point where the <code class="docutils literal"><span class="pre">Builder</span></code> is set up. The first line
creates a new <a class="reference external" href="http://en.wikipedia.org/wiki/Basic_block">basic block</a>
(named &#8220;entry&#8221;), which is inserted into <code class="docutils literal"><span class="pre">TheFunction</span></code>. The second line
then tells the builder that new instructions should be inserted into the
end of the new basic block. Basic blocks in LLVM are an important part
of functions that define the <a class="reference external" href="http://en.wikipedia.org/wiki/Control_flow_graph">Control Flow
Graph</a>. Since we
don&#8217;t have any control flow, our functions will only contain one block
at this point. We&#8217;ll fix this in <a class="reference external" href="LangImpl5.html">Chapter 5</a> :).</p>
<p>Next we add the function arguments to the NamedValues map (after first clearing
it out) so that they&#8217;re accessible to <code class="docutils literal"><span class="pre">VariableExprAST</span></code> nodes.</p>
<div class="highlight-c++"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="p">(</span><span class="n">Value</span> <span class="o">*</span><span class="n">RetVal</span> <span class="o">=</span> <span class="n">Body</span><span class="o">-&gt;</span><span class="n">codegen</span><span class="p">())</span> <span class="p">{</span>
  <span class="c1">// Finish off the function.</span>
  <span class="n">Builder</span><span class="p">.</span><span class="n">CreateRet</span><span class="p">(</span><span class="n">RetVal</span><span class="p">);</span>

  <span class="c1">// Validate the generated code, checking for consistency.</span>
  <span class="n">verifyFunction</span><span class="p">(</span><span class="o">*</span><span class="n">TheFunction</span><span class="p">);</span>

  <span class="k">return</span> <span class="n">TheFunction</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Once the insertion point has been set up and the NamedValues map populated,
we call the <code class="docutils literal"><span class="pre">codegen()</span></code> method for the root expression of the function. If no
error happens, this emits code to compute the expression into the entry block
and returns the value that was computed. Assuming no error, we then create an
LLVM <a class="reference external" href="../LangRef.html#ret-instruction">ret instruction</a>, which completes the function.
Once the function is built, we call <code class="docutils literal"><span class="pre">verifyFunction</span></code>, which is
provided by LLVM. This function does a variety of consistency checks on
the generated code, to determine if our compiler is doing everything
right. Using this is important: it can catch a lot of bugs. Once the
function is finished and validated, we return it.</p>
<div class="highlight-c++"><div class="highlight"><pre><span></span>  <span class="c1">// Error reading body, remove function.</span>
  <span class="n">TheFunction</span><span class="o">-&gt;</span><span class="n">eraseFromParent</span><span class="p">();</span>
  <span class="k">return</span> <span class="k">nullptr</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The only piece left here is handling of the error case. For simplicity,
we handle this by merely deleting the function we produced with the
<code class="docutils literal"><span class="pre">eraseFromParent</span></code> method. This allows the user to redefine a function
that they incorrectly typed in before: if we didn&#8217;t delete it, it would
live in the symbol table, with a body, preventing future redefinition.</p>
<p>This code does have a bug, though: If the <code class="docutils literal"><span class="pre">FunctionAST::codegen()</span></code> method
finds an existing IR Function, it does not validate its signature against the
definition&#8217;s own prototype. This means that an earlier &#8216;extern&#8217; declaration will
take precedence over the function definition&#8217;s signature, which can cause
codegen to fail, for instance if the function arguments are named differently.
There are a number of ways to fix this bug, see what you can come up with! Here
is a testcase:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">extern</span> <span class="n">foo</span><span class="p">(</span><span class="n">a</span><span class="p">);</span>     <span class="c1"># ok, defines foo.</span>
<span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">b</span><span class="p">)</span> <span class="n">b</span><span class="p">;</span>      <span class="c1"># Error: Unknown variable name. (decl using &#39;a&#39; takes precedence).</span>
</pre></div>
</div>
</div>
<div class="section" id="driver-changes-and-closing-thoughts">
<h2><a class="toc-backref" href="#id5">3.5. Driver Changes and Closing Thoughts</a><a class="headerlink" href="#driver-changes-and-closing-thoughts" title="Permalink to this headline">¶</a></h2>
<p>For now, code generation to LLVM doesn&#8217;t really get us much, except that
we can look at the pretty IR calls. The sample code inserts calls to
codegen into the &#8220;<code class="docutils literal"><span class="pre">HandleDefinition</span></code>&#8221;, &#8220;<code class="docutils literal"><span class="pre">HandleExtern</span></code>&#8221; etc
functions, and then dumps out the LLVM IR. This gives a nice way to look
at the LLVM IR for simple functions. For example:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">ready</span><span class="o">&gt;</span> <span class="mi">4</span><span class="o">+</span><span class="mi">5</span><span class="p">;</span>
<span class="n">Read</span> <span class="n">top</span><span class="o">-</span><span class="n">level</span> <span class="n">expression</span><span class="p">:</span>
<span class="n">define</span> <span class="n">double</span> <span class="nd">@0</span><span class="p">()</span> <span class="p">{</span>
<span class="n">entry</span><span class="p">:</span>
  <span class="n">ret</span> <span class="n">double</span> <span class="mf">9.000000e+00</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Note how the parser turns the top-level expression into anonymous
functions for us. This will be handy when we add <a class="reference external" href="LangImpl4.html#adding-a-jit-compiler">JIT
support</a> in the next chapter. Also note that the
code is very literally transcribed, no optimizations are being performed
except simple constant folding done by IRBuilder. We will <a class="reference external" href="LangImpl4.html#trivial-constant-folding">add
optimizations</a> explicitly in the next
chapter.</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">ready</span><span class="o">&gt;</span> <span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">a</span> <span class="n">b</span><span class="p">)</span> <span class="n">a</span><span class="o">*</span><span class="n">a</span> <span class="o">+</span> <span class="mi">2</span><span class="o">*</span><span class="n">a</span><span class="o">*</span><span class="n">b</span> <span class="o">+</span> <span class="n">b</span><span class="o">*</span><span class="n">b</span><span class="p">;</span>
<span class="n">Read</span> <span class="n">function</span> <span class="n">definition</span><span class="p">:</span>
<span class="n">define</span> <span class="n">double</span> <span class="nd">@foo</span><span class="p">(</span><span class="n">double</span> <span class="o">%</span><span class="n">a</span><span class="p">,</span> <span class="n">double</span> <span class="o">%</span><span class="n">b</span><span class="p">)</span> <span class="p">{</span>
<span class="n">entry</span><span class="p">:</span>
  <span class="o">%</span><span class="n">multmp</span> <span class="o">=</span> <span class="n">fmul</span> <span class="n">double</span> <span class="o">%</span><span class="n">a</span><span class="p">,</span> <span class="o">%</span><span class="n">a</span>
  <span class="o">%</span><span class="n">multmp1</span> <span class="o">=</span> <span class="n">fmul</span> <span class="n">double</span> <span class="mf">2.000000e+00</span><span class="p">,</span> <span class="o">%</span><span class="n">a</span>
  <span class="o">%</span><span class="n">multmp2</span> <span class="o">=</span> <span class="n">fmul</span> <span class="n">double</span> <span class="o">%</span><span class="n">multmp1</span><span class="p">,</span> <span class="o">%</span><span class="n">b</span>
  <span class="o">%</span><span class="n">addtmp</span> <span class="o">=</span> <span class="n">fadd</span> <span class="n">double</span> <span class="o">%</span><span class="n">multmp</span><span class="p">,</span> <span class="o">%</span><span class="n">multmp2</span>
  <span class="o">%</span><span class="n">multmp3</span> <span class="o">=</span> <span class="n">fmul</span> <span class="n">double</span> <span class="o">%</span><span class="n">b</span><span class="p">,</span> <span class="o">%</span><span class="n">b</span>
  <span class="o">%</span><span class="n">addtmp4</span> <span class="o">=</span> <span class="n">fadd</span> <span class="n">double</span> <span class="o">%</span><span class="n">addtmp</span><span class="p">,</span> <span class="o">%</span><span class="n">multmp3</span>
  <span class="n">ret</span> <span class="n">double</span> <span class="o">%</span><span class="n">addtmp4</span>
<span class="p">}</span>
</pre></div>
</div>
<p>This shows some simple arithmetic. Notice the striking similarity to the
LLVM builder calls that we use to create the instructions.</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">ready</span><span class="o">&gt;</span> <span class="k">def</span> <span class="nf">bar</span><span class="p">(</span><span class="n">a</span><span class="p">)</span> <span class="n">foo</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="mf">4.0</span><span class="p">)</span> <span class="o">+</span> <span class="n">bar</span><span class="p">(</span><span class="mi">31337</span><span class="p">);</span>
<span class="n">Read</span> <span class="n">function</span> <span class="n">definition</span><span class="p">:</span>
<span class="n">define</span> <span class="n">double</span> <span class="nd">@bar</span><span class="p">(</span><span class="n">double</span> <span class="o">%</span><span class="n">a</span><span class="p">)</span> <span class="p">{</span>
<span class="n">entry</span><span class="p">:</span>
  <span class="o">%</span><span class="n">calltmp</span> <span class="o">=</span> <span class="n">call</span> <span class="n">double</span> <span class="nd">@foo</span><span class="p">(</span><span class="n">double</span> <span class="o">%</span><span class="n">a</span><span class="p">,</span> <span class="n">double</span> <span class="mf">4.000000e+00</span><span class="p">)</span>
  <span class="o">%</span><span class="n">calltmp1</span> <span class="o">=</span> <span class="n">call</span> <span class="n">double</span> <span class="nd">@bar</span><span class="p">(</span><span class="n">double</span> <span class="mf">3.133700e+04</span><span class="p">)</span>
  <span class="o">%</span><span class="n">addtmp</span> <span class="o">=</span> <span class="n">fadd</span> <span class="n">double</span> <span class="o">%</span><span class="n">calltmp</span><span class="p">,</span> <span class="o">%</span><span class="n">calltmp1</span>
  <span class="n">ret</span> <span class="n">double</span> <span class="o">%</span><span class="n">addtmp</span>
<span class="p">}</span>
</pre></div>
</div>
<p>This shows some function calls. Note that this function will take a long
time to execute if you call it. In the future we&#8217;ll add conditional
control flow to actually make recursion useful :).</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">ready</span><span class="o">&gt;</span> <span class="n">extern</span> <span class="n">cos</span><span class="p">(</span><span class="n">x</span><span class="p">);</span>
<span class="n">Read</span> <span class="n">extern</span><span class="p">:</span>
<span class="n">declare</span> <span class="n">double</span> <span class="nd">@cos</span><span class="p">(</span><span class="n">double</span><span class="p">)</span>

<span class="n">ready</span><span class="o">&gt;</span> <span class="n">cos</span><span class="p">(</span><span class="mf">1.234</span><span class="p">);</span>
<span class="n">Read</span> <span class="n">top</span><span class="o">-</span><span class="n">level</span> <span class="n">expression</span><span class="p">:</span>
<span class="n">define</span> <span class="n">double</span> <span class="nd">@1</span><span class="p">()</span> <span class="p">{</span>
<span class="n">entry</span><span class="p">:</span>
  <span class="o">%</span><span class="n">calltmp</span> <span class="o">=</span> <span class="n">call</span> <span class="n">double</span> <span class="nd">@cos</span><span class="p">(</span><span class="n">double</span> <span class="mf">1.234000e+00</span><span class="p">)</span>
  <span class="n">ret</span> <span class="n">double</span> <span class="o">%</span><span class="n">calltmp</span>
<span class="p">}</span>
</pre></div>
</div>
<p>This shows an extern for the libm &#8220;cos&#8221; function, and a call to it.</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">ready</span><span class="o">&gt;</span> <span class="o">^</span><span class="n">D</span>
<span class="p">;</span> <span class="n">ModuleID</span> <span class="o">=</span> <span class="s1">&#39;my cool jit&#39;</span>

<span class="n">define</span> <span class="n">double</span> <span class="nd">@0</span><span class="p">()</span> <span class="p">{</span>
<span class="n">entry</span><span class="p">:</span>
  <span class="o">%</span><span class="n">addtmp</span> <span class="o">=</span> <span class="n">fadd</span> <span class="n">double</span> <span class="mf">4.000000e+00</span><span class="p">,</span> <span class="mf">5.000000e+00</span>
  <span class="n">ret</span> <span class="n">double</span> <span class="o">%</span><span class="n">addtmp</span>
<span class="p">}</span>

<span class="n">define</span> <span class="n">double</span> <span class="nd">@foo</span><span class="p">(</span><span class="n">double</span> <span class="o">%</span><span class="n">a</span><span class="p">,</span> <span class="n">double</span> <span class="o">%</span><span class="n">b</span><span class="p">)</span> <span class="p">{</span>
<span class="n">entry</span><span class="p">:</span>
  <span class="o">%</span><span class="n">multmp</span> <span class="o">=</span> <span class="n">fmul</span> <span class="n">double</span> <span class="o">%</span><span class="n">a</span><span class="p">,</span> <span class="o">%</span><span class="n">a</span>
  <span class="o">%</span><span class="n">multmp1</span> <span class="o">=</span> <span class="n">fmul</span> <span class="n">double</span> <span class="mf">2.000000e+00</span><span class="p">,</span> <span class="o">%</span><span class="n">a</span>
  <span class="o">%</span><span class="n">multmp2</span> <span class="o">=</span> <span class="n">fmul</span> <span class="n">double</span> <span class="o">%</span><span class="n">multmp1</span><span class="p">,</span> <span class="o">%</span><span class="n">b</span>
  <span class="o">%</span><span class="n">addtmp</span> <span class="o">=</span> <span class="n">fadd</span> <span class="n">double</span> <span class="o">%</span><span class="n">multmp</span><span class="p">,</span> <span class="o">%</span><span class="n">multmp2</span>
  <span class="o">%</span><span class="n">multmp3</span> <span class="o">=</span> <span class="n">fmul</span> <span class="n">double</span> <span class="o">%</span><span class="n">b</span><span class="p">,</span> <span class="o">%</span><span class="n">b</span>
  <span class="o">%</span><span class="n">addtmp4</span> <span class="o">=</span> <span class="n">fadd</span> <span class="n">double</span> <span class="o">%</span><span class="n">addtmp</span><span class="p">,</span> <span class="o">%</span><span class="n">multmp3</span>
  <span class="n">ret</span> <span class="n">double</span> <span class="o">%</span><span class="n">addtmp4</span>
<span class="p">}</span>

<span class="n">define</span> <span class="n">double</span> <span class="nd">@bar</span><span class="p">(</span><span class="n">double</span> <span class="o">%</span><span class="n">a</span><span class="p">)</span> <span class="p">{</span>
<span class="n">entry</span><span class="p">:</span>
  <span class="o">%</span><span class="n">calltmp</span> <span class="o">=</span> <span class="n">call</span> <span class="n">double</span> <span class="nd">@foo</span><span class="p">(</span><span class="n">double</span> <span class="o">%</span><span class="n">a</span><span class="p">,</span> <span class="n">double</span> <span class="mf">4.000000e+00</span><span class="p">)</span>
  <span class="o">%</span><span class="n">calltmp1</span> <span class="o">=</span> <span class="n">call</span> <span class="n">double</span> <span class="nd">@bar</span><span class="p">(</span><span class="n">double</span> <span class="mf">3.133700e+04</span><span class="p">)</span>
  <span class="o">%</span><span class="n">addtmp</span> <span class="o">=</span> <span class="n">fadd</span> <span class="n">double</span> <span class="o">%</span><span class="n">calltmp</span><span class="p">,</span> <span class="o">%</span><span class="n">calltmp1</span>
  <span class="n">ret</span> <span class="n">double</span> <span class="o">%</span><span class="n">addtmp</span>
<span class="p">}</span>

<span class="n">declare</span> <span class="n">double</span> <span class="nd">@cos</span><span class="p">(</span><span class="n">double</span><span class="p">)</span>

<span class="n">define</span> <span class="n">double</span> <span class="nd">@1</span><span class="p">()</span> <span class="p">{</span>
<span class="n">entry</span><span class="p">:</span>
  <span class="o">%</span><span class="n">calltmp</span> <span class="o">=</span> <span class="n">call</span> <span class="n">double</span> <span class="nd">@cos</span><span class="p">(</span><span class="n">double</span> <span class="mf">1.234000e+00</span><span class="p">)</span>
  <span class="n">ret</span> <span class="n">double</span> <span class="o">%</span><span class="n">calltmp</span>
<span class="p">}</span>
</pre></div>
</div>
<p>When you quit the current demo (by sending an EOF via CTRL+D on Linux
or CTRL+Z and ENTER on Windows), it dumps out the IR for the entire
module generated. Here you can see the big picture with all the
functions referencing each other.</p>
<p>This wraps up the third chapter of the Kaleidoscope tutorial. Up next,
we&#8217;ll describe how to <a class="reference external" href="LangImpl4.html">add JIT codegen and optimizer
support</a> to this so we can actually start running
code!</p>
</div>
<div class="section" id="full-code-listing">
<h2><a class="toc-backref" href="#id6">3.6. Full Code Listing</a><a class="headerlink" href="#full-code-listing" title="Permalink to this headline">¶</a></h2>
<p>Here is the complete code listing for our running example, enhanced with
the LLVM code generator. Because this uses the LLVM libraries, we need
to link them in. To do this, we use the
<a class="reference external" href="http://llvm.org/cmds/llvm-config.html">llvm-config</a> tool to inform
our makefile/command line about which options to use:</p>
<div class="highlight-bash"><div class="highlight"><pre><span></span><span class="c1"># Compile</span>
clang++ -g -O3 toy.cpp <span class="sb">`</span>llvm-config --cxxflags --ldflags --system-libs --libs core<span class="sb">`</span> -o toy
<span class="c1"># Run</span>
./toy
</pre></div>
</div>
<p>Here is the code:</p>
<div class="highlight-c++"><div class="highlight"><pre><span></span><span class="cp">#include</span> <span class="cpf">&quot;llvm/ADT/APFloat.h&quot;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&quot;llvm/ADT/STLExtras.h&quot;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&quot;llvm/IR/BasicBlock.h&quot;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&quot;llvm/IR/Constants.h&quot;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&quot;llvm/IR/DerivedTypes.h&quot;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&quot;llvm/IR/Function.h&quot;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&quot;llvm/IR/IRBuilder.h&quot;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&quot;llvm/IR/LLVMContext.h&quot;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&quot;llvm/IR/Module.h&quot;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&quot;llvm/IR/Type.h&quot;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&quot;llvm/IR/Verifier.h&quot;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&lt;algorithm&gt;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&lt;cctype&gt;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&lt;cstdio&gt;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&lt;cstdlib&gt;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&lt;map&gt;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&lt;memory&gt;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&lt;string&gt;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&lt;vector&gt;</span><span class="cp"></span>

<span class="k">using</span> <span class="k">namespace</span> <span class="n">llvm</span><span class="p">;</span>

<span class="c1">//===----------------------------------------------------------------------===//</span>
<span class="c1">// Lexer</span>
<span class="c1">//===----------------------------------------------------------------------===//</span>

<span class="c1">// The lexer returns tokens [0-255] if it is an unknown character, otherwise one</span>
<span class="c1">// of these for known things.</span>
<span class="k">enum</span> <span class="n">Token</span> <span class="p">{</span>
  <span class="n">tok_eof</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span>

  <span class="c1">// commands</span>
  <span class="n">tok_def</span> <span class="o">=</span> <span class="o">-</span><span class="mi">2</span><span class="p">,</span>
  <span class="n">tok_extern</span> <span class="o">=</span> <span class="o">-</span><span class="mi">3</span><span class="p">,</span>

  <span class="c1">// primary</span>
  <span class="n">tok_identifier</span> <span class="o">=</span> <span class="o">-</span><span class="mi">4</span><span class="p">,</span>
  <span class="n">tok_number</span> <span class="o">=</span> <span class="o">-</span><span class="mi">5</span>
<span class="p">};</span>

<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">IdentifierStr</span><span class="p">;</span> <span class="c1">// Filled in if tok_identifier</span>
<span class="k">static</span> <span class="kt">double</span> <span class="n">NumVal</span><span class="p">;</span>             <span class="c1">// Filled in if tok_number</span>

<span class="c1">/// gettok - Return the next token from standard input.</span>
<span class="k">static</span> <span class="kt">int</span> <span class="nf">gettok</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">static</span> <span class="kt">int</span> <span class="n">LastChar</span> <span class="o">=</span> <span class="sc">&#39; &#39;</span><span class="p">;</span>

  <span class="c1">// Skip any whitespace.</span>
  <span class="k">while</span> <span class="p">(</span><span class="n">isspace</span><span class="p">(</span><span class="n">LastChar</span><span class="p">))</span>
    <span class="n">LastChar</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">();</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">isalpha</span><span class="p">(</span><span class="n">LastChar</span><span class="p">))</span> <span class="p">{</span> <span class="c1">// identifier: [a-zA-Z][a-zA-Z0-9]*</span>
    <span class="n">IdentifierStr</span> <span class="o">=</span> <span class="n">LastChar</span><span class="p">;</span>
    <span class="k">while</span> <span class="p">(</span><span class="n">isalnum</span><span class="p">((</span><span class="n">LastChar</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">())))</span>
      <span class="n">IdentifierStr</span> <span class="o">+=</span> <span class="n">LastChar</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;def&quot;</span><span class="p">)</span>
      <span class="k">return</span> <span class="n">tok_def</span><span class="p">;</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;extern&quot;</span><span class="p">)</span>
      <span class="k">return</span> <span class="n">tok_extern</span><span class="p">;</span>
    <span class="k">return</span> <span class="n">tok_identifier</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">isdigit</span><span class="p">(</span><span class="n">LastChar</span><span class="p">)</span> <span class="o">||</span> <span class="n">LastChar</span> <span class="o">==</span> <span class="sc">&#39;.&#39;</span><span class="p">)</span> <span class="p">{</span> <span class="c1">// Number: [0-9.]+</span>
    <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">NumStr</span><span class="p">;</span>
    <span class="k">do</span> <span class="p">{</span>
      <span class="n">NumStr</span> <span class="o">+=</span> <span class="n">LastChar</span><span class="p">;</span>
      <span class="n">LastChar</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">();</span>
    <span class="p">}</span> <span class="k">while</span> <span class="p">(</span><span class="n">isdigit</span><span class="p">(</span><span class="n">LastChar</span><span class="p">)</span> <span class="o">||</span> <span class="n">LastChar</span> <span class="o">==</span> <span class="sc">&#39;.&#39;</span><span class="p">);</span>

    <span class="n">NumVal</span> <span class="o">=</span> <span class="n">strtod</span><span class="p">(</span><span class="n">NumStr</span><span class="p">.</span><span class="n">c_str</span><span class="p">(),</span> <span class="k">nullptr</span><span class="p">);</span>
    <span class="k">return</span> <span class="n">tok_number</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">LastChar</span> <span class="o">==</span> <span class="sc">&#39;#&#39;</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// Comment until end of line.</span>
    <span class="k">do</span>
      <span class="n">LastChar</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">();</span>
    <span class="k">while</span> <span class="p">(</span><span class="n">LastChar</span> <span class="o">!=</span> <span class="n">EOF</span> <span class="o">&amp;&amp;</span> <span class="n">LastChar</span> <span class="o">!=</span> <span class="sc">&#39;\n&#39;</span> <span class="o">&amp;&amp;</span> <span class="n">LastChar</span> <span class="o">!=</span> <span class="sc">&#39;\r&#39;</span><span class="p">);</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">LastChar</span> <span class="o">!=</span> <span class="n">EOF</span><span class="p">)</span>
      <span class="k">return</span> <span class="n">gettok</span><span class="p">();</span>
  <span class="p">}</span>

  <span class="c1">// Check for end of file.  Don&#39;t eat the EOF.</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">LastChar</span> <span class="o">==</span> <span class="n">EOF</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">tok_eof</span><span class="p">;</span>

  <span class="c1">// Otherwise, just return the character as its ascii value.</span>
  <span class="kt">int</span> <span class="n">ThisChar</span> <span class="o">=</span> <span class="n">LastChar</span><span class="p">;</span>
  <span class="n">LastChar</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">();</span>
  <span class="k">return</span> <span class="n">ThisChar</span><span class="p">;</span>
<span class="p">}</span>

<span class="c1">//===----------------------------------------------------------------------===//</span>
<span class="c1">// Abstract Syntax Tree (aka Parse Tree)</span>
<span class="c1">//===----------------------------------------------------------------------===//</span>

<span class="k">namespace</span> <span class="p">{</span>

<span class="c1">/// ExprAST - Base class for all expression nodes.</span>
<span class="k">class</span> <span class="nc">ExprAST</span> <span class="p">{</span>
<span class="k">public</span><span class="o">:</span>
  <span class="k">virtual</span> <span class="o">~</span><span class="n">ExprAST</span><span class="p">()</span> <span class="o">=</span> <span class="k">default</span><span class="p">;</span>

  <span class="k">virtual</span> <span class="n">Value</span> <span class="o">*</span><span class="nf">codegen</span><span class="p">()</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">};</span>

<span class="c1">/// NumberExprAST - Expression class for numeric literals like &quot;1.0&quot;.</span>
<span class="k">class</span> <span class="nc">NumberExprAST</span> <span class="o">:</span> <span class="k">public</span> <span class="n">ExprAST</span> <span class="p">{</span>
  <span class="kt">double</span> <span class="n">Val</span><span class="p">;</span>

<span class="k">public</span><span class="o">:</span>
  <span class="n">NumberExprAST</span><span class="p">(</span><span class="kt">double</span> <span class="n">Val</span><span class="p">)</span> <span class="o">:</span> <span class="n">Val</span><span class="p">(</span><span class="n">Val</span><span class="p">)</span> <span class="p">{}</span>

  <span class="n">Value</span> <span class="o">*</span><span class="n">codegen</span><span class="p">()</span> <span class="k">override</span><span class="p">;</span>
<span class="p">};</span>

<span class="c1">/// VariableExprAST - Expression class for referencing a variable, like &quot;a&quot;.</span>
<span class="k">class</span> <span class="nc">VariableExprAST</span> <span class="o">:</span> <span class="k">public</span> <span class="n">ExprAST</span> <span class="p">{</span>
  <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">Name</span><span class="p">;</span>

<span class="k">public</span><span class="o">:</span>
  <span class="n">VariableExprAST</span><span class="p">(</span><span class="k">const</span> <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="o">&amp;</span><span class="n">Name</span><span class="p">)</span> <span class="o">:</span> <span class="n">Name</span><span class="p">(</span><span class="n">Name</span><span class="p">)</span> <span class="p">{}</span>

  <span class="n">Value</span> <span class="o">*</span><span class="n">codegen</span><span class="p">()</span> <span class="k">override</span><span class="p">;</span>
<span class="p">};</span>

<span class="c1">/// BinaryExprAST - Expression class for a binary operator.</span>
<span class="k">class</span> <span class="nc">BinaryExprAST</span> <span class="o">:</span> <span class="k">public</span> <span class="n">ExprAST</span> <span class="p">{</span>
  <span class="kt">char</span> <span class="n">Op</span><span class="p">;</span>
  <span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">ExprAST</span><span class="o">&gt;</span> <span class="n">LHS</span><span class="p">,</span> <span class="n">RHS</span><span class="p">;</span>

<span class="k">public</span><span class="o">:</span>
  <span class="n">BinaryExprAST</span><span class="p">(</span><span class="kt">char</span> <span class="n">Op</span><span class="p">,</span> <span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">ExprAST</span><span class="o">&gt;</span> <span class="n">LHS</span><span class="p">,</span>
                <span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">ExprAST</span><span class="o">&gt;</span> <span class="n">RHS</span><span class="p">)</span>
      <span class="o">:</span> <span class="n">Op</span><span class="p">(</span><span class="n">Op</span><span class="p">),</span> <span class="n">LHS</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">LHS</span><span class="p">)),</span> <span class="n">RHS</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">RHS</span><span class="p">))</span> <span class="p">{}</span>

  <span class="n">Value</span> <span class="o">*</span><span class="n">codegen</span><span class="p">()</span> <span class="k">override</span><span class="p">;</span>
<span class="p">};</span>

<span class="c1">/// CallExprAST - Expression class for function calls.</span>
<span class="k">class</span> <span class="nc">CallExprAST</span> <span class="o">:</span> <span class="k">public</span> <span class="n">ExprAST</span> <span class="p">{</span>
  <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">Callee</span><span class="p">;</span>
  <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">ExprAST</span><span class="o">&gt;&gt;</span> <span class="n">Args</span><span class="p">;</span>

<span class="k">public</span><span class="o">:</span>
  <span class="n">CallExprAST</span><span class="p">(</span><span class="k">const</span> <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="o">&amp;</span><span class="n">Callee</span><span class="p">,</span>
              <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">ExprAST</span><span class="o">&gt;&gt;</span> <span class="n">Args</span><span class="p">)</span>
      <span class="o">:</span> <span class="n">Callee</span><span class="p">(</span><span class="n">Callee</span><span class="p">),</span> <span class="n">Args</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">Args</span><span class="p">))</span> <span class="p">{}</span>

  <span class="n">Value</span> <span class="o">*</span><span class="n">codegen</span><span class="p">()</span> <span class="k">override</span><span class="p">;</span>
<span class="p">};</span>

<span class="c1">/// PrototypeAST - This class represents the &quot;prototype&quot; for a function,</span>
<span class="c1">/// which captures its name, and its argument names (thus implicitly the number</span>
<span class="c1">/// of arguments the function takes).</span>
<span class="k">class</span> <span class="nc">PrototypeAST</span> <span class="p">{</span>
  <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">Name</span><span class="p">;</span>
  <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">&gt;</span> <span class="n">Args</span><span class="p">;</span>

<span class="k">public</span><span class="o">:</span>
  <span class="n">PrototypeAST</span><span class="p">(</span><span class="k">const</span> <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="o">&amp;</span><span class="n">Name</span><span class="p">,</span> <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">&gt;</span> <span class="n">Args</span><span class="p">)</span>
      <span class="o">:</span> <span class="n">Name</span><span class="p">(</span><span class="n">Name</span><span class="p">),</span> <span class="n">Args</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">Args</span><span class="p">))</span> <span class="p">{}</span>

  <span class="n">Function</span> <span class="o">*</span><span class="n">codegen</span><span class="p">();</span>
  <span class="k">const</span> <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="o">&amp;</span><span class="n">getName</span><span class="p">()</span> <span class="k">const</span> <span class="p">{</span> <span class="k">return</span> <span class="n">Name</span><span class="p">;</span> <span class="p">}</span>
<span class="p">};</span>

<span class="c1">/// FunctionAST - This class represents a function definition itself.</span>
<span class="k">class</span> <span class="nc">FunctionAST</span> <span class="p">{</span>
  <span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">PrototypeAST</span><span class="o">&gt;</span> <span class="n">Proto</span><span class="p">;</span>
  <span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">ExprAST</span><span class="o">&gt;</span> <span class="n">Body</span><span class="p">;</span>

<span class="k">public</span><span class="o">:</span>
  <span class="n">FunctionAST</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">PrototypeAST</span><span class="o">&gt;</span> <span class="n">Proto</span><span class="p">,</span>
              <span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">ExprAST</span><span class="o">&gt;</span> <span class="n">Body</span><span class="p">)</span>
      <span class="o">:</span> <span class="n">Proto</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">Proto</span><span class="p">)),</span> <span class="n">Body</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">Body</span><span class="p">))</span> <span class="p">{}</span>

  <span class="n">Function</span> <span class="o">*</span><span class="n">codegen</span><span class="p">();</span>
<span class="p">};</span>

<span class="p">}</span> <span class="c1">// end anonymous namespace</span>

<span class="c1">//===----------------------------------------------------------------------===//</span>
<span class="c1">// Parser</span>
<span class="c1">//===----------------------------------------------------------------------===//</span>

<span class="c1">/// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current</span>
<span class="c1">/// token the parser is looking at.  getNextToken reads another token from the</span>
<span class="c1">/// lexer and updates CurTok with its results.</span>
<span class="k">static</span> <span class="kt">int</span> <span class="n">CurTok</span><span class="p">;</span>
<span class="k">static</span> <span class="kt">int</span> <span class="nf">getNextToken</span><span class="p">()</span> <span class="p">{</span> <span class="k">return</span> <span class="n">CurTok</span> <span class="o">=</span> <span class="n">gettok</span><span class="p">();</span> <span class="p">}</span>

<span class="c1">/// BinopPrecedence - This holds the precedence for each binary operator that is</span>
<span class="c1">/// defined.</span>
<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">map</span><span class="o">&lt;</span><span class="kt">char</span><span class="p">,</span> <span class="kt">int</span><span class="o">&gt;</span> <span class="n">BinopPrecedence</span><span class="p">;</span>

<span class="c1">/// GetTokPrecedence - Get the precedence of the pending binary operator token.</span>
<span class="k">static</span> <span class="kt">int</span> <span class="nf">GetTokPrecedence</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">isascii</span><span class="p">(</span><span class="n">CurTok</span><span class="p">))</span>
    <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>

  <span class="c1">// Make sure it&#39;s a declared binop.</span>
  <span class="kt">int</span> <span class="n">TokPrec</span> <span class="o">=</span> <span class="n">BinopPrecedence</span><span class="p">[</span><span class="n">CurTok</span><span class="p">];</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">TokPrec</span> <span class="o">&lt;=</span> <span class="mi">0</span><span class="p">)</span>
    <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
  <span class="k">return</span> <span class="n">TokPrec</span><span class="p">;</span>
<span class="p">}</span>

<span class="c1">/// LogError* - These are little helper functions for error handling.</span>
<span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">ExprAST</span><span class="o">&gt;</span> <span class="n">LogError</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">Str</span><span class="p">)</span> <span class="p">{</span>
  <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;Error: %s</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span> <span class="n">Str</span><span class="p">);</span>
  <span class="k">return</span> <span class="k">nullptr</span><span class="p">;</span>
<span class="p">}</span>

<span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">PrototypeAST</span><span class="o">&gt;</span> <span class="n">LogErrorP</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">Str</span><span class="p">)</span> <span class="p">{</span>
  <span class="n">LogError</span><span class="p">(</span><span class="n">Str</span><span class="p">);</span>
  <span class="k">return</span> <span class="k">nullptr</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">ExprAST</span><span class="o">&gt;</span> <span class="n">ParseExpression</span><span class="p">();</span>

<span class="c1">/// numberexpr ::= number</span>
<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">ExprAST</span><span class="o">&gt;</span> <span class="n">ParseNumberExpr</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">auto</span> <span class="n">Result</span> <span class="o">=</span> <span class="n">llvm</span><span class="o">::</span><span class="n">make_unique</span><span class="o">&lt;</span><span class="n">NumberExprAST</span><span class="o">&gt;</span><span class="p">(</span><span class="n">NumVal</span><span class="p">);</span>
  <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// consume the number</span>
  <span class="k">return</span> <span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">Result</span><span class="p">);</span>
<span class="p">}</span>

<span class="c1">/// parenexpr ::= &#39;(&#39; expression &#39;)&#39;</span>
<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">ExprAST</span><span class="o">&gt;</span> <span class="n">ParseParenExpr</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// eat (.</span>
  <span class="k">auto</span> <span class="n">V</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">V</span><span class="p">)</span>
    <span class="k">return</span> <span class="k">nullptr</span><span class="p">;</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="sc">&#39;)&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">LogError</span><span class="p">(</span><span class="s">&quot;expected &#39;)&#39;&quot;</span><span class="p">);</span>
  <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// eat ).</span>
  <span class="k">return</span> <span class="n">V</span><span class="p">;</span>
<span class="p">}</span>

<span class="c1">/// identifierexpr</span>
<span class="c1">///   ::= identifier</span>
<span class="c1">///   ::= identifier &#39;(&#39; expression* &#39;)&#39;</span>
<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">ExprAST</span><span class="o">&gt;</span> <span class="n">ParseIdentifierExpr</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">IdName</span> <span class="o">=</span> <span class="n">IdentifierStr</span><span class="p">;</span>

  <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// eat identifier.</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="sc">&#39;(&#39;</span><span class="p">)</span> <span class="c1">// Simple variable ref.</span>
    <span class="k">return</span> <span class="n">llvm</span><span class="o">::</span><span class="n">make_unique</span><span class="o">&lt;</span><span class="n">VariableExprAST</span><span class="o">&gt;</span><span class="p">(</span><span class="n">IdName</span><span class="p">);</span>

  <span class="c1">// Call.</span>
  <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// eat (</span>
  <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">ExprAST</span><span class="o">&gt;&gt;</span> <span class="n">Args</span><span class="p">;</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="sc">&#39;)&#39;</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">while</span> <span class="p">(</span><span class="nb">true</span><span class="p">)</span> <span class="p">{</span>
      <span class="k">if</span> <span class="p">(</span><span class="k">auto</span> <span class="n">Arg</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">())</span>
        <span class="n">Args</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">Arg</span><span class="p">));</span>
      <span class="k">else</span>
        <span class="k">return</span> <span class="k">nullptr</span><span class="p">;</span>

      <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">==</span> <span class="sc">&#39;)&#39;</span><span class="p">)</span>
        <span class="k">break</span><span class="p">;</span>

      <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="sc">&#39;,&#39;</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">LogError</span><span class="p">(</span><span class="s">&quot;Expected &#39;)&#39; or &#39;,&#39; in argument list&quot;</span><span class="p">);</span>
      <span class="n">getNextToken</span><span class="p">();</span>
    <span class="p">}</span>
  <span class="p">}</span>

  <span class="c1">// Eat the &#39;)&#39;.</span>
  <span class="n">getNextToken</span><span class="p">();</span>

  <span class="k">return</span> <span class="n">llvm</span><span class="o">::</span><span class="n">make_unique</span><span class="o">&lt;</span><span class="n">CallExprAST</span><span class="o">&gt;</span><span class="p">(</span><span class="n">IdName</span><span class="p">,</span> <span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">Args</span><span class="p">));</span>
<span class="p">}</span>

<span class="c1">/// primary</span>
<span class="c1">///   ::= identifierexpr</span>
<span class="c1">///   ::= numberexpr</span>
<span class="c1">///   ::= parenexpr</span>
<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">ExprAST</span><span class="o">&gt;</span> <span class="n">ParsePrimary</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">switch</span> <span class="p">(</span><span class="n">CurTok</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">default</span><span class="o">:</span>
    <span class="k">return</span> <span class="n">LogError</span><span class="p">(</span><span class="s">&quot;unknown token when expecting an expression&quot;</span><span class="p">);</span>
  <span class="k">case</span> <span class="nl">tok_identifier</span><span class="p">:</span>
    <span class="k">return</span> <span class="n">ParseIdentifierExpr</span><span class="p">();</span>
  <span class="k">case</span> <span class="nl">tok_number</span><span class="p">:</span>
    <span class="k">return</span> <span class="n">ParseNumberExpr</span><span class="p">();</span>
  <span class="k">case</span> <span class="sc">&#39;(&#39;</span><span class="o">:</span>
    <span class="k">return</span> <span class="n">ParseParenExpr</span><span class="p">();</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="c1">/// binoprhs</span>
<span class="c1">///   ::= (&#39;+&#39; primary)*</span>
<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">ExprAST</span><span class="o">&gt;</span> <span class="n">ParseBinOpRHS</span><span class="p">(</span><span class="kt">int</span> <span class="n">ExprPrec</span><span class="p">,</span>
                                              <span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">ExprAST</span><span class="o">&gt;</span> <span class="n">LHS</span><span class="p">)</span> <span class="p">{</span>
  <span class="c1">// If this is a binop, find its precedence.</span>
  <span class="k">while</span> <span class="p">(</span><span class="nb">true</span><span class="p">)</span> <span class="p">{</span>
    <span class="kt">int</span> <span class="n">TokPrec</span> <span class="o">=</span> <span class="n">GetTokPrecedence</span><span class="p">();</span>

    <span class="c1">// If this is a binop that binds at least as tightly as the current binop,</span>
    <span class="c1">// consume it, otherwise we are done.</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">TokPrec</span> <span class="o">&lt;</span> <span class="n">ExprPrec</span><span class="p">)</span>
      <span class="k">return</span> <span class="n">LHS</span><span class="p">;</span>

    <span class="c1">// Okay, we know this is a binop.</span>
    <span class="kt">int</span> <span class="n">BinOp</span> <span class="o">=</span> <span class="n">CurTok</span><span class="p">;</span>
    <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// eat binop</span>

    <span class="c1">// Parse the primary expression after the binary operator.</span>
    <span class="k">auto</span> <span class="n">RHS</span> <span class="o">=</span> <span class="n">ParsePrimary</span><span class="p">();</span>
    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">RHS</span><span class="p">)</span>
      <span class="k">return</span> <span class="k">nullptr</span><span class="p">;</span>

    <span class="c1">// If BinOp binds less tightly with RHS than the operator after RHS, let</span>
    <span class="c1">// the pending operator take RHS as its LHS.</span>
    <span class="kt">int</span> <span class="n">NextPrec</span> <span class="o">=</span> <span class="n">GetTokPrecedence</span><span class="p">();</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">TokPrec</span> <span class="o">&lt;</span> <span class="n">NextPrec</span><span class="p">)</span> <span class="p">{</span>
      <span class="n">RHS</span> <span class="o">=</span> <span class="n">ParseBinOpRHS</span><span class="p">(</span><span class="n">TokPrec</span> <span class="o">+</span> <span class="mi">1</span><span class="p">,</span> <span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">RHS</span><span class="p">));</span>
      <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">RHS</span><span class="p">)</span>
        <span class="k">return</span> <span class="k">nullptr</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="c1">// Merge LHS/RHS.</span>
    <span class="n">LHS</span> <span class="o">=</span>
        <span class="n">llvm</span><span class="o">::</span><span class="n">make_unique</span><span class="o">&lt;</span><span class="n">BinaryExprAST</span><span class="o">&gt;</span><span class="p">(</span><span class="n">BinOp</span><span class="p">,</span> <span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">LHS</span><span class="p">),</span> <span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">RHS</span><span class="p">));</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="c1">/// expression</span>
<span class="c1">///   ::= primary binoprhs</span>
<span class="c1">///</span>
<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">ExprAST</span><span class="o">&gt;</span> <span class="n">ParseExpression</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">auto</span> <span class="n">LHS</span> <span class="o">=</span> <span class="n">ParsePrimary</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">LHS</span><span class="p">)</span>
    <span class="k">return</span> <span class="k">nullptr</span><span class="p">;</span>

  <span class="k">return</span> <span class="nf">ParseBinOpRHS</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">LHS</span><span class="p">));</span>
<span class="p">}</span>

<span class="c1">/// prototype</span>
<span class="c1">///   ::= id &#39;(&#39; id* &#39;)&#39;</span>
<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">PrototypeAST</span><span class="o">&gt;</span> <span class="n">ParsePrototype</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="n">tok_identifier</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">LogErrorP</span><span class="p">(</span><span class="s">&quot;Expected function name in prototype&quot;</span><span class="p">);</span>

  <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">FnName</span> <span class="o">=</span> <span class="n">IdentifierStr</span><span class="p">;</span>
  <span class="n">getNextToken</span><span class="p">();</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="sc">&#39;(&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">LogErrorP</span><span class="p">(</span><span class="s">&quot;Expected &#39;(&#39; in prototype&quot;</span><span class="p">);</span>

  <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">&gt;</span> <span class="n">ArgNames</span><span class="p">;</span>
  <span class="k">while</span> <span class="p">(</span><span class="n">getNextToken</span><span class="p">()</span> <span class="o">==</span> <span class="n">tok_identifier</span><span class="p">)</span>
    <span class="n">ArgNames</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="n">IdentifierStr</span><span class="p">);</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="sc">&#39;)&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">LogErrorP</span><span class="p">(</span><span class="s">&quot;Expected &#39;)&#39; in prototype&quot;</span><span class="p">);</span>

  <span class="c1">// success.</span>
  <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// eat &#39;)&#39;.</span>

  <span class="k">return</span> <span class="n">llvm</span><span class="o">::</span><span class="n">make_unique</span><span class="o">&lt;</span><span class="n">PrototypeAST</span><span class="o">&gt;</span><span class="p">(</span><span class="n">FnName</span><span class="p">,</span> <span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">ArgNames</span><span class="p">));</span>
<span class="p">}</span>

<span class="c1">/// definition ::= &#39;def&#39; prototype expression</span>
<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">FunctionAST</span><span class="o">&gt;</span> <span class="n">ParseDefinition</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// eat def.</span>
  <span class="k">auto</span> <span class="n">Proto</span> <span class="o">=</span> <span class="n">ParsePrototype</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">Proto</span><span class="p">)</span>
    <span class="k">return</span> <span class="k">nullptr</span><span class="p">;</span>

  <span class="k">if</span> <span class="p">(</span><span class="k">auto</span> <span class="n">E</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">())</span>
    <span class="k">return</span> <span class="n">llvm</span><span class="o">::</span><span class="n">make_unique</span><span class="o">&lt;</span><span class="n">FunctionAST</span><span class="o">&gt;</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">Proto</span><span class="p">),</span> <span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">E</span><span class="p">));</span>
  <span class="k">return</span> <span class="k">nullptr</span><span class="p">;</span>
<span class="p">}</span>

<span class="c1">/// toplevelexpr ::= expression</span>
<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">FunctionAST</span><span class="o">&gt;</span> <span class="n">ParseTopLevelExpr</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span><span class="k">auto</span> <span class="n">E</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">())</span> <span class="p">{</span>
    <span class="c1">// Make an anonymous proto.</span>
    <span class="k">auto</span> <span class="n">Proto</span> <span class="o">=</span> <span class="n">llvm</span><span class="o">::</span><span class="n">make_unique</span><span class="o">&lt;</span><span class="n">PrototypeAST</span><span class="o">&gt;</span><span class="p">(</span><span class="s">&quot;__anon_expr&quot;</span><span class="p">,</span>
                                                 <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">&gt;</span><span class="p">());</span>
    <span class="k">return</span> <span class="n">llvm</span><span class="o">::</span><span class="n">make_unique</span><span class="o">&lt;</span><span class="n">FunctionAST</span><span class="o">&gt;</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">Proto</span><span class="p">),</span> <span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">E</span><span class="p">));</span>
  <span class="p">}</span>
  <span class="k">return</span> <span class="k">nullptr</span><span class="p">;</span>
<span class="p">}</span>

<span class="c1">/// external ::= &#39;extern&#39; prototype</span>
<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">PrototypeAST</span><span class="o">&gt;</span> <span class="n">ParseExtern</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// eat extern.</span>
  <span class="k">return</span> <span class="nf">ParsePrototype</span><span class="p">();</span>
<span class="p">}</span>

<span class="c1">//===----------------------------------------------------------------------===//</span>
<span class="c1">// Code Generation</span>
<span class="c1">//===----------------------------------------------------------------------===//</span>

<span class="k">static</span> <span class="n">LLVMContext</span> <span class="n">TheContext</span><span class="p">;</span>
<span class="k">static</span> <span class="n">IRBuilder</span><span class="o">&lt;&gt;</span> <span class="n">Builder</span><span class="p">(</span><span class="n">TheContext</span><span class="p">);</span>
<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">Module</span><span class="o">&gt;</span> <span class="n">TheModule</span><span class="p">;</span>
<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">map</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="p">,</span> <span class="n">Value</span> <span class="o">*&gt;</span> <span class="n">NamedValues</span><span class="p">;</span>

<span class="n">Value</span> <span class="o">*</span><span class="nf">LogErrorV</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">Str</span><span class="p">)</span> <span class="p">{</span>
  <span class="n">LogError</span><span class="p">(</span><span class="n">Str</span><span class="p">);</span>
  <span class="k">return</span> <span class="k">nullptr</span><span class="p">;</span>
<span class="p">}</span>

<span class="n">Value</span> <span class="o">*</span><span class="n">NumberExprAST</span><span class="o">::</span><span class="n">codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">return</span> <span class="n">ConstantFP</span><span class="o">::</span><span class="n">get</span><span class="p">(</span><span class="n">TheContext</span><span class="p">,</span> <span class="n">APFloat</span><span class="p">(</span><span class="n">Val</span><span class="p">));</span>
<span class="p">}</span>

<span class="n">Value</span> <span class="o">*</span><span class="n">VariableExprAST</span><span class="o">::</span><span class="n">codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="c1">// Look this variable up in the function.</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">V</span> <span class="o">=</span> <span class="n">NamedValues</span><span class="p">[</span><span class="n">Name</span><span class="p">];</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">V</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">LogErrorV</span><span class="p">(</span><span class="s">&quot;Unknown variable name&quot;</span><span class="p">);</span>
  <span class="k">return</span> <span class="n">V</span><span class="p">;</span>
<span class="p">}</span>

<span class="n">Value</span> <span class="o">*</span><span class="n">BinaryExprAST</span><span class="o">::</span><span class="n">codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">L</span> <span class="o">=</span> <span class="n">LHS</span><span class="o">-&gt;</span><span class="n">codegen</span><span class="p">();</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">R</span> <span class="o">=</span> <span class="n">RHS</span><span class="o">-&gt;</span><span class="n">codegen</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">L</span> <span class="o">||</span> <span class="o">!</span><span class="n">R</span><span class="p">)</span>
    <span class="k">return</span> <span class="k">nullptr</span><span class="p">;</span>

  <span class="k">switch</span> <span class="p">(</span><span class="n">Op</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">case</span> <span class="sc">&#39;+&#39;</span><span class="o">:</span>
    <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFAdd</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">R</span><span class="p">,</span> <span class="s">&quot;addtmp&quot;</span><span class="p">);</span>
  <span class="k">case</span> <span class="sc">&#39;-&#39;</span><span class="o">:</span>
    <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFSub</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">R</span><span class="p">,</span> <span class="s">&quot;subtmp&quot;</span><span class="p">);</span>
  <span class="k">case</span> <span class="sc">&#39;*&#39;</span><span class="o">:</span>
    <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFMul</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">R</span><span class="p">,</span> <span class="s">&quot;multmp&quot;</span><span class="p">);</span>
  <span class="k">case</span> <span class="sc">&#39;&lt;&#39;</span><span class="o">:</span>
    <span class="n">L</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFCmpULT</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">R</span><span class="p">,</span> <span class="s">&quot;cmptmp&quot;</span><span class="p">);</span>
    <span class="c1">// Convert bool 0/1 to double 0.0 or 1.0</span>
    <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateUIToFP</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">Type</span><span class="o">::</span><span class="n">getDoubleTy</span><span class="p">(</span><span class="n">TheContext</span><span class="p">),</span> <span class="s">&quot;booltmp&quot;</span><span class="p">);</span>
  <span class="k">default</span><span class="o">:</span>
    <span class="k">return</span> <span class="n">LogErrorV</span><span class="p">(</span><span class="s">&quot;invalid binary operator&quot;</span><span class="p">);</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="n">Value</span> <span class="o">*</span><span class="n">CallExprAST</span><span class="o">::</span><span class="n">codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="c1">// Look up the name in the global module table.</span>
  <span class="n">Function</span> <span class="o">*</span><span class="n">CalleeF</span> <span class="o">=</span> <span class="n">TheModule</span><span class="o">-&gt;</span><span class="n">getFunction</span><span class="p">(</span><span class="n">Callee</span><span class="p">);</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">CalleeF</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">LogErrorV</span><span class="p">(</span><span class="s">&quot;Unknown function referenced&quot;</span><span class="p">);</span>

  <span class="c1">// If argument mismatch error.</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">CalleeF</span><span class="o">-&gt;</span><span class="n">arg_size</span><span class="p">()</span> <span class="o">!=</span> <span class="n">Args</span><span class="p">.</span><span class="n">size</span><span class="p">())</span>
    <span class="k">return</span> <span class="n">LogErrorV</span><span class="p">(</span><span class="s">&quot;Incorrect # arguments passed&quot;</span><span class="p">);</span>

  <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">Value</span> <span class="o">*&gt;</span> <span class="n">ArgsV</span><span class="p">;</span>
  <span class="k">for</span> <span class="p">(</span><span class="kt">unsigned</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="n">e</span> <span class="o">=</span> <span class="n">Args</span><span class="p">.</span><span class="n">size</span><span class="p">();</span> <span class="n">i</span> <span class="o">!=</span> <span class="n">e</span><span class="p">;</span> <span class="o">++</span><span class="n">i</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">ArgsV</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="n">Args</span><span class="p">[</span><span class="n">i</span><span class="p">]</span><span class="o">-&gt;</span><span class="n">codegen</span><span class="p">());</span>
    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">ArgsV</span><span class="p">.</span><span class="n">back</span><span class="p">())</span>
      <span class="k">return</span> <span class="k">nullptr</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateCall</span><span class="p">(</span><span class="n">CalleeF</span><span class="p">,</span> <span class="n">ArgsV</span><span class="p">,</span> <span class="s">&quot;calltmp&quot;</span><span class="p">);</span>
<span class="p">}</span>

<span class="n">Function</span> <span class="o">*</span><span class="n">PrototypeAST</span><span class="o">::</span><span class="n">codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="c1">// Make the function type:  double(double,double) etc.</span>
  <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">Type</span> <span class="o">*&gt;</span> <span class="n">Doubles</span><span class="p">(</span><span class="n">Args</span><span class="p">.</span><span class="n">size</span><span class="p">(),</span> <span class="n">Type</span><span class="o">::</span><span class="n">getDoubleTy</span><span class="p">(</span><span class="n">TheContext</span><span class="p">));</span>
  <span class="n">FunctionType</span> <span class="o">*</span><span class="n">FT</span> <span class="o">=</span>
      <span class="n">FunctionType</span><span class="o">::</span><span class="n">get</span><span class="p">(</span><span class="n">Type</span><span class="o">::</span><span class="n">getDoubleTy</span><span class="p">(</span><span class="n">TheContext</span><span class="p">),</span> <span class="n">Doubles</span><span class="p">,</span> <span class="nb">false</span><span class="p">);</span>

  <span class="n">Function</span> <span class="o">*</span><span class="n">F</span> <span class="o">=</span>
      <span class="n">Function</span><span class="o">::</span><span class="n">Create</span><span class="p">(</span><span class="n">FT</span><span class="p">,</span> <span class="n">Function</span><span class="o">::</span><span class="n">ExternalLinkage</span><span class="p">,</span> <span class="n">Name</span><span class="p">,</span> <span class="n">TheModule</span><span class="p">.</span><span class="n">get</span><span class="p">());</span>

  <span class="c1">// Set names for all arguments.</span>
  <span class="kt">unsigned</span> <span class="n">Idx</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
  <span class="k">for</span> <span class="p">(</span><span class="k">auto</span> <span class="o">&amp;</span><span class="nl">Arg</span> <span class="p">:</span> <span class="n">F</span><span class="o">-&gt;</span><span class="n">args</span><span class="p">())</span>
    <span class="n">Arg</span><span class="p">.</span><span class="n">setName</span><span class="p">(</span><span class="n">Args</span><span class="p">[</span><span class="n">Idx</span><span class="o">++</span><span class="p">]);</span>

  <span class="k">return</span> <span class="n">F</span><span class="p">;</span>
<span class="p">}</span>

<span class="n">Function</span> <span class="o">*</span><span class="n">FunctionAST</span><span class="o">::</span><span class="n">codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="c1">// First, check for an existing function from a previous &#39;extern&#39; declaration.</span>
  <span class="n">Function</span> <span class="o">*</span><span class="n">TheFunction</span> <span class="o">=</span> <span class="n">TheModule</span><span class="o">-&gt;</span><span class="n">getFunction</span><span class="p">(</span><span class="n">Proto</span><span class="o">-&gt;</span><span class="n">getName</span><span class="p">());</span>

  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">TheFunction</span><span class="p">)</span>
    <span class="n">TheFunction</span> <span class="o">=</span> <span class="n">Proto</span><span class="o">-&gt;</span><span class="n">codegen</span><span class="p">();</span>

  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">TheFunction</span><span class="p">)</span>
    <span class="k">return</span> <span class="k">nullptr</span><span class="p">;</span>

  <span class="c1">// Create a new basic block to start insertion into.</span>
  <span class="n">BasicBlock</span> <span class="o">*</span><span class="n">BB</span> <span class="o">=</span> <span class="n">BasicBlock</span><span class="o">::</span><span class="n">Create</span><span class="p">(</span><span class="n">TheContext</span><span class="p">,</span> <span class="s">&quot;entry&quot;</span><span class="p">,</span> <span class="n">TheFunction</span><span class="p">);</span>
  <span class="n">Builder</span><span class="p">.</span><span class="n">SetInsertPoint</span><span class="p">(</span><span class="n">BB</span><span class="p">);</span>

  <span class="c1">// Record the function arguments in the NamedValues map.</span>
  <span class="n">NamedValues</span><span class="p">.</span><span class="n">clear</span><span class="p">();</span>
  <span class="k">for</span> <span class="p">(</span><span class="k">auto</span> <span class="o">&amp;</span><span class="nl">Arg</span> <span class="p">:</span> <span class="n">TheFunction</span><span class="o">-&gt;</span><span class="n">args</span><span class="p">())</span>
    <span class="n">NamedValues</span><span class="p">[</span><span class="n">Arg</span><span class="p">.</span><span class="n">getName</span><span class="p">()]</span> <span class="o">=</span> <span class="o">&amp;</span><span class="n">Arg</span><span class="p">;</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">Value</span> <span class="o">*</span><span class="n">RetVal</span> <span class="o">=</span> <span class="n">Body</span><span class="o">-&gt;</span><span class="n">codegen</span><span class="p">())</span> <span class="p">{</span>
    <span class="c1">// Finish off the function.</span>
    <span class="n">Builder</span><span class="p">.</span><span class="n">CreateRet</span><span class="p">(</span><span class="n">RetVal</span><span class="p">);</span>

    <span class="c1">// Validate the generated code, checking for consistency.</span>
    <span class="n">verifyFunction</span><span class="p">(</span><span class="o">*</span><span class="n">TheFunction</span><span class="p">);</span>

    <span class="k">return</span> <span class="n">TheFunction</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="c1">// Error reading body, remove function.</span>
  <span class="n">TheFunction</span><span class="o">-&gt;</span><span class="n">eraseFromParent</span><span class="p">();</span>
  <span class="k">return</span> <span class="k">nullptr</span><span class="p">;</span>
<span class="p">}</span>

<span class="c1">//===----------------------------------------------------------------------===//</span>
<span class="c1">// Top-Level parsing and JIT Driver</span>
<span class="c1">//===----------------------------------------------------------------------===//</span>

<span class="k">static</span> <span class="kt">void</span> <span class="n">HandleDefinition</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span><span class="k">auto</span> <span class="n">FnAST</span> <span class="o">=</span> <span class="n">ParseDefinition</span><span class="p">())</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="k">auto</span> <span class="o">*</span><span class="n">FnIR</span> <span class="o">=</span> <span class="n">FnAST</span><span class="o">-&gt;</span><span class="n">codegen</span><span class="p">())</span> <span class="p">{</span>
      <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;Read function definition:&quot;</span><span class="p">);</span>
      <span class="n">FnIR</span><span class="o">-&gt;</span><span class="n">print</span><span class="p">(</span><span class="n">errs</span><span class="p">());</span>
      <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">);</span>
    <span class="p">}</span>
  <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
    <span class="c1">// Skip token for error recovery.</span>
    <span class="n">getNextToken</span><span class="p">();</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="k">static</span> <span class="kt">void</span> <span class="n">HandleExtern</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span><span class="k">auto</span> <span class="n">ProtoAST</span> <span class="o">=</span> <span class="n">ParseExtern</span><span class="p">())</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="k">auto</span> <span class="o">*</span><span class="n">FnIR</span> <span class="o">=</span> <span class="n">ProtoAST</span><span class="o">-&gt;</span><span class="n">codegen</span><span class="p">())</span> <span class="p">{</span>
      <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;Read extern: &quot;</span><span class="p">);</span>
      <span class="n">FnIR</span><span class="o">-&gt;</span><span class="n">print</span><span class="p">(</span><span class="n">errs</span><span class="p">());</span>
      <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">);</span>
    <span class="p">}</span>
  <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
    <span class="c1">// Skip token for error recovery.</span>
    <span class="n">getNextToken</span><span class="p">();</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="k">static</span> <span class="kt">void</span> <span class="n">HandleTopLevelExpression</span><span class="p">()</span> <span class="p">{</span>
  <span class="c1">// Evaluate a top-level expression into an anonymous function.</span>
  <span class="k">if</span> <span class="p">(</span><span class="k">auto</span> <span class="n">FnAST</span> <span class="o">=</span> <span class="n">ParseTopLevelExpr</span><span class="p">())</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="k">auto</span> <span class="o">*</span><span class="n">FnIR</span> <span class="o">=</span> <span class="n">FnAST</span><span class="o">-&gt;</span><span class="n">codegen</span><span class="p">())</span> <span class="p">{</span>
      <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;Read top-level expression:&quot;</span><span class="p">);</span>
      <span class="n">FnIR</span><span class="o">-&gt;</span><span class="n">print</span><span class="p">(</span><span class="n">errs</span><span class="p">());</span>
      <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">);</span>
    <span class="p">}</span>
  <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
    <span class="c1">// Skip token for error recovery.</span>
    <span class="n">getNextToken</span><span class="p">();</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="c1">/// top ::= definition | external | expression | &#39;;&#39;</span>
<span class="k">static</span> <span class="kt">void</span> <span class="n">MainLoop</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">while</span> <span class="p">(</span><span class="nb">true</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;ready&gt; &quot;</span><span class="p">);</span>
    <span class="k">switch</span> <span class="p">(</span><span class="n">CurTok</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">case</span> <span class="nl">tok_eof</span><span class="p">:</span>
      <span class="k">return</span><span class="p">;</span>
    <span class="k">case</span> <span class="sc">&#39;;&#39;</span><span class="o">:</span> <span class="c1">// ignore top-level semicolons.</span>
      <span class="n">getNextToken</span><span class="p">();</span>
      <span class="k">break</span><span class="p">;</span>
    <span class="k">case</span> <span class="nl">tok_def</span><span class="p">:</span>
      <span class="n">HandleDefinition</span><span class="p">();</span>
      <span class="k">break</span><span class="p">;</span>
    <span class="k">case</span> <span class="nl">tok_extern</span><span class="p">:</span>
      <span class="n">HandleExtern</span><span class="p">();</span>
      <span class="k">break</span><span class="p">;</span>
    <span class="k">default</span><span class="o">:</span>
      <span class="n">HandleTopLevelExpression</span><span class="p">();</span>
      <span class="k">break</span><span class="p">;</span>
    <span class="p">}</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="c1">//===----------------------------------------------------------------------===//</span>
<span class="c1">// Main driver code.</span>
<span class="c1">//===----------------------------------------------------------------------===//</span>

<span class="kt">int</span> <span class="n">main</span><span class="p">()</span> <span class="p">{</span>
  <span class="c1">// Install standard binary operators.</span>
  <span class="c1">// 1 is lowest precedence.</span>
  <span class="n">BinopPrecedence</span><span class="p">[</span><span class="sc">&#39;&lt;&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">10</span><span class="p">;</span>
  <span class="n">BinopPrecedence</span><span class="p">[</span><span class="sc">&#39;+&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">20</span><span class="p">;</span>
  <span class="n">BinopPrecedence</span><span class="p">[</span><span class="sc">&#39;-&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">20</span><span class="p">;</span>
  <span class="n">BinopPrecedence</span><span class="p">[</span><span class="sc">&#39;*&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">40</span><span class="p">;</span> <span class="c1">// highest.</span>

  <span class="c1">// Prime the first token.</span>
  <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;ready&gt; &quot;</span><span class="p">);</span>
  <span class="n">getNextToken</span><span class="p">();</span>

  <span class="c1">// Make the module, which holds all the code.</span>
  <span class="n">TheModule</span> <span class="o">=</span> <span class="n">llvm</span><span class="o">::</span><span class="n">make_unique</span><span class="o">&lt;</span><span class="n">Module</span><span class="o">&gt;</span><span class="p">(</span><span class="s">&quot;my cool jit&quot;</span><span class="p">,</span> <span class="n">TheContext</span><span class="p">);</span>

  <span class="c1">// Run the main &quot;interpreter loop&quot; now.</span>
  <span class="n">MainLoop</span><span class="p">();</span>

  <span class="c1">// Print out all of the generated code.</span>
  <span class="n">TheModule</span><span class="o">-&gt;</span><span class="n">print</span><span class="p">(</span><span class="n">errs</span><span class="p">(),</span> <span class="k">nullptr</span><span class="p">);</span>

  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p><a class="reference external" href="LangImpl04.html">Next: Adding JIT and Optimizer Support</a></p>
</div>
</div>


          </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="LangImpl04.html" title="4. Kaleidoscope: Adding JIT and Optimizer Support"
             >next</a> |</li>
        <li class="right" >
          <a href="LangImpl02.html" title="2. Kaleidoscope: Implementing a Parser and AST"
             >previous</a> |</li>
  <li><a href="http://llvm.org/">LLVM Home</a>&nbsp;|&nbsp;</li>
  <li><a href="../index.html">Documentation</a>&raquo;</li>

          <li class="nav-item nav-item-1"><a href="index.html" >LLVM Tutorial: Table of Contents</a> &#187;</li> 
      </ul>
    </div>
    <div class="footer" role="contentinfo">
        &#169; Copyright 2003-2017, LLVM Project.
      Last updated on 2017-06-30.
      Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.5.1.
    </div>
  </body>
</html>